import React, { useEffect, useRef, useState } from 'react';
import { Checkbox } from 'antd';
import styles from './index.module.scss';
import AvatorCropper from '@/app/components/AvatorCropper';
import { upload } from '@/service';
import { getFileNameFromURL } from '@/util';
import { blobToFile } from '@/app/utils';

// import Checkbox from '@/app/components/Checkbox/checkbox'

export default function Avator(props: any) {
  const [visible, setVisible] = useState(false);
  const [photo, setPhoto] = useState(props.photo);
  const [url, setUrl] = useState(props.photo);
  const [name, setName] = useState('');
  useEffect(() => {
    setPhoto(props.photo);
    setUrl(props.photo?.split('?')?.[0] || '');
  }, [props.photo]);
  const FileRef = useRef<HTMLInputElement>(null);
  function uploadImg(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
      alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种');

      return false;
    }
    setName(file?.name || '');
    const reader = new FileReader();
    reader.onload = (e) => {
      let data = '';
      if (typeof e.target?.result === 'object') {
        data = window.URL.createObjectURL(new Blob([e.target?.result as any]));
      } else {
        data = e.target?.result || '';
      }
      setUrl(data);
      setVisible(true);
    };
    reader.readAsArrayBuffer(file as File);
  }

  function onChange(blob: Blob, width: number) {
    let fileName = FileRef.current?.files[0]?.name;
    let fileType = FileRef.current?.files[0]?.type;
    if (!fileName) {
      fileName = getFileNameFromURL(url);
    }
    if (!fileType) {
      fileType = `image/${fileName.split('.')[1]}`;
    }
    const file = blobToFile(blob, fileName, fileType);
    if (FileRef.current) {
      FileRef.current.value = '';
    }
    setVisible(false);
    const formData = new FormData();

    formData.append('file', file);
    upload(formData).then((res) => {
      if (width >= 600) {
        setPhoto(`${res.data}?imageView2/2/w/400`);
        props.photoChange(`${res.data}?imageView2/2/w/400`);
      } else {
        setPhoto(res.data);
        props.photoChange(res.data);
      }

      setVisible(false);
    });
  }
  return (
    <>
      <div className={styles.avator}>
        <div className={styles.photoWrap}>
          {
            <>
              {photo ? (
                <img
                  src={photo}
                  alt=""
                  style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                  onClick={() => {
                    setVisible(true);
                  }}
                />
              ) : (
                <label
                  htmlFor="uploads"
                  style={{ display: 'inline-block', marginTop: '20px' }}
                >
                  <div className={styles.defaultPhoto}>
                    <svg
                      version="1.1"
                      viewBox="0 0 36 36"
                      preserveAspectRatio="xMidYMid meet"
                      fill="white"
                    >
                      <path d="M32,8H24.7L23.64,5.28A2,2,0,0,0,21.78,4H14.22a2,2,0,0,0-1.87,1.28L11.3,8H4a2,2,0,0,0-2,2V30a2,2,0,0,0,2,2H32a2,2,0,0,0,2-2V10A2,2,0,0,0,32,8ZM6.17,13.63a.8.8,0,0,1,0-1.6h2.4a.8.8,0,0,1,0,1.6ZM18,28a9,9,0,1,1,9-9A9,9,0,0,1,18,28Z"></path>
                      <path d="M11.11,19.06a7.07,7.07,0,0,0,4.11,6.41l1.09-1.74a5,5,0,1,1,5.22-8.39l1.09-1.76a7.06,7.06,0,0,0-11.51,5.48Z"></path>
                      <rect
                        x="0"
                        y="0"
                        width="36"
                        height="36"
                        fillOpacity="0"
                      ></rect>
                    </svg>
                  </div>
                </label>
              )}
            </>
          }
          {/* <div style={
            { marginTop: '10px' }
          }>
            <Checkbox checked={props.showPhoto} onChange={(e) => {
              props.changeShowPhoto(e.target.checked)
            }}>显示头像</Checkbox>
          </div> */}
          <input
            type="file"
            id="uploads"
            ref={FileRef}
            style={{
              position: 'absolute',
              left: '10px',
              clip: 'rect(0 0 0 0)',
            }}
            accept="image/*"
            onChange={uploadImg}
          />
        </div>
      </div>
      {visible ? (
        <AvatorCropper
          src={url}
          name={name}
          fileRef={FileRef}
          onChange={onChange}
          onClose={() => {
            setVisible(false);
          }}
          onDelete={() => {
            setVisible(false);
            props.photoChange('');
          }}
        ></AvatorCropper>
      ) : null}
    </>
  );
}
